import { LitElement, html, css } from 'lit';
import { classMap } from 'lit/directives/class-map.js';

class ACReveal extends LitElement {
  static properties = {
    trigger: { 
      type: String,
      hasChanged: (oldValue, newValue) => {
        console.log('trigger changed', oldValue, newValue);
      }
    },
    autoreset: { type: Boolean },
    visible: { type: Boolean, reflect: true }
  }

  constructor() {
    super();
    /** @type {'click' | 'hover'} */
    this.trigger = this.trigger || 'hover';
    this.autoreset = false;
    this.visible = false;
  }

  static get styles() {
    return css`
      .content ::slotted(*) {
        transition: background-color 0.3s ease;
      }
      .hidden ::slotted(*) {
        background-color: black;
      }
      ::slotted(*):focus {
        background-color: black;
      }
    `;
  }

  connectedCallback() {
    console.log(this.trigger)
    super.connectedCallback();
    if (this.trigger === 'hover') {
      this.addEventListener('mouseenter', this.handleEvent);
      this.addEventListener('mouseleave', this.handleEvent);
    } else {
      this.addEventListener('click', this.handleEvent);
      this.addEventListener('focusout', this.hide);
    }
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    this.removeEventListener('mouseenter', this.handleEvent);
    this.removeEventListener('mouseleave', this.handleEvent);
    this.removeEventListener('click', this.show);
  }

  show() {
    this.visible = true;
    // if (this.autoreset && this.trigger === 'click')
    //   // 等待 DOM 渲染后再添加事件
    //   window.setTimeout(() => document.addEventListener('click', () => this.hide()));
  }

  hide() {
    this.visible = false;
    document.removeEventListener('click', () => this.hide(), 100);
  }

  toggle() {
    this.visible = !this.visible;
  }

  willUpdate(changedProperties) {
    // 判断改变的属性，改变事件监听
  }

  /** @param {Event} e */
  handleEvent(e) {
    console.log(e.type, this.trigger);
    if (e.type === 'click' && this.trigger === 'click') {
      e.stopPropagation();
      this.toggle();
    }
    // else if (e.type === 'focusout')
    //   this.hide();
    else if (e.type === 'mouseenter' && this.trigger === 'hover')
      this.show();
    else if (e.type === 'mouseleave' && this.trigger === 'hover' && this.autoreset)
      this.hide();
  }

  render() {
    const classes = {
      hidden: !this.visible
    };
    return html`
      <div class="content ${classMap(classes)}" tabindex="0">
        <slot></slot>
      </div>
      <div tabindex="1">123</div>
    `;
  }
}

customElements.define('ac-reveal', ACReveal);